package org.doubango.FrCall;

import java.util.Collection;

import org.doubango.FrCall.Screens.BaseScreen;
import org.doubango.FrCall.Services.Impl.OpenfireTask;
import org.doubango.FrCall.Utils.SystemMessageManager;
import org.doubango.FrCall.model.SystemMessage;
import org.doubango.FrCall.model.User;
import org.doubango.ngn.NgnApplication;
import org.doubango.ngn.utils.NgnConfigurationEntry;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smackx.GroupChatInvitation;
import org.jivesoftware.smackx.PrivateDataManager;
import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
import org.jivesoftware.smackx.packet.ChatStateExtension;
import org.jivesoftware.smackx.packet.LastActivity;
import org.jivesoftware.smackx.packet.OfflineMessageInfo;
import org.jivesoftware.smackx.packet.OfflineMessageRequest;
import org.jivesoftware.smackx.packet.SharedGroupsInfo;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;
import org.jivesoftware.smackx.provider.DataFormProvider;
import org.jivesoftware.smackx.provider.DelayInformationProvider;
import org.jivesoftware.smackx.provider.DiscoverInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverItemsProvider;
import org.jivesoftware.smackx.provider.MUCAdminProvider;
import org.jivesoftware.smackx.provider.MUCOwnerProvider;
import org.jivesoftware.smackx.provider.MUCUserProvider;
import org.jivesoftware.smackx.provider.MessageEventProvider;
import org.jivesoftware.smackx.provider.MultipleAddressesProvider;
import org.jivesoftware.smackx.provider.RosterExchangeProvider;
import org.jivesoftware.smackx.provider.StreamInitiationProvider;
import org.jivesoftware.smackx.provider.VCardProvider;
import org.jivesoftware.smackx.provider.XHTMLExtensionProvider;
import org.jivesoftware.smackx.search.UserSearch;
import org.jivesoftware.smackx.search.UserSearchManager;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
 
public class OpenfireNetService extends Service {
	private final static String TAG = OpenfireNetService.class
			.getCanonicalName();
	public final static int REQUEST_LOGIN = 0;
	public final static int REQUEST_LOGOUT = 1;
	public final static int RESPONSE_LOGIN_SUCCESS = 2;
	public final static int RESPONSE_LOGIN_FAIL = 3;
	public final static int RESPONSE_LOGOUT_SUCCESS = 4;
	public final static int RESPONSE_LOGOUT_FAIL = 5;
	public final static int REQUEST_LOAD_CARD = 6;
	public final static int REQUEST_SAVE_CARD = 7;
	public final static int RESPONSE_LOAD_CARD = 8;
	public final static int RESPONSE_SAVE_CARD = 9;
	public final static int CONNECT_TO_SERVICER = 10;
	public final static int RESPONSE_CONNECT_TO_SERVICER = 11;
	public static String HostIP;
	public static XMPPConnection mConnection;
	public static String userId;
	public static ConnectionConfiguration connectionConfig;
	public static UserSearchManager search;
	public static ChatManager cm;
	public static FileTransferManager fm;
	public static String searchService;
	private static VCard tempCard; 
	public static Resources resources;

    public interface ICountService {
    	public abstract int getCount();
    }
    private ServiceBinder serviceBinder=new ServiceBinder();
    public class ServiceBinder extends Binder implements ICountService{
    	@Override
    	public int getCount() {
    		return 0;
    	}        
    }
	BroadcastReceiver br = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String actio_Id = intent.getAction();
			if(actio_Id.equals(resources.getString(R.string.OPENFIRE_ACTION_REQ_LOGIN)))
			{
				String username = intent.getStringExtra(resources.getString(R.string.REQ_LOGIN_USERNAME));
				String password = intent.getStringExtra(resources.getString(R.string.REQ_LOGIN_PASSWORD));
				String status = intent.getStringExtra(resources.getString(R.string.REQ_LOGIN_STATUS));
				Bundle bundle = new Bundle();
				bundle.putString(resources.getString(R.string.REQ_LOGIN_USERNAME), username);
				bundle.putString(resources.getString(R.string.REQ_LOGIN_PASSWORD), password);
				bundle.putString(resources.getString(R.string.REQ_LOGIN_STATUS), status);
				Message msg = new Message();
				msg.what = REQUEST_LOGIN;
				msg.setData(bundle);
				getListHander().sendMessage(msg);
			}
			if(actio_Id.equals(resources.getString(R.string.OPENFIRE_ACTION_REQ_LOAD_CARD)))
			{
				String username = intent.getStringExtra(resources.getString(R.string.REQ_CARD_USER));
				Bundle bundle = new Bundle();
				bundle.putString(resources.getString(R.string.REQ_CARD_USER), username);
				Message msg = new Message();
				msg.what = REQUEST_LOAD_CARD;
				msg.setData(bundle);
				getListHander().sendMessage(msg);
			}
		}
	};
	public void onCreate() {
		super.onCreate();
		resources = this.getResources();
		IntentFilter filter = new IntentFilter(); // 和广播中Intent的action对应
		filter.addAction(resources.getString(R.string.OPENFIRE_ACTION_REQ_LOGIN));
		filter.addAction(resources.getString(R.string.OPENFIRE_ACTION_REQ_LOGOUT));
		filter.addAction(resources.getString(R.string.OPENFIRE_ACTION_REQ_LOAD_CARD));
		filter.addAction(resources.getString(R.string.OPENFIRE_ACTION_REQ_SAVE_CARD));
        registerReceiver(br, filter);
		setConfig(AppConfig.WANGJING_IP);
		
//		goodNet();
	};
	public String goodNet(Context context) { 
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);    
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();    
        if (networkinfo == null || !networkinfo.isAvailable()) {
//FIXME AlertDialog只能在activity里用        	
//        	new AlertDialog.Builder(this).setMessage("没有可以使用的网络").setPositiveButton("Ok", null).show();
            Toast.makeText(context, "没有可以使用的网络", Toast.LENGTH_SHORT).show();
            return null;  
        }  
////        new AlertDialog.Builder(this).setMessage("网络正常可以使用").setPositiveButton("Ok", null).show();
        String result = checkNetworkInfo(context);
        Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
        return result;
    }   
    
    private String checkNetworkInfo(Context context) {
    	String result = null;
    	ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        //mobile 3G Data Network
    	State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
    	if(mobile.compareTo(State.CONNECTED)==0)
    	{
    		result = "移动网络已连接";
    	}
//        new AlertDialog.Builder(this).setMessage(mobile.toString()).setPositiveButton("3G", null).show();//显示3G网络连接状态  	
//        Toast.makeText(getApplicationContext(), "3G的连接状态：" + mobile.toString(), Toast.LENGTH_SHORT).show();
    	State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    	
    	if(wifi.compareTo(State.CONNECTED)==0)
    	{
    		result = "WIFI已连接";
    	}
//    	new AlertDialog.Builder(this).setMessage(wifi.toString()).setPositiveButton("WIFI", null).show();//显示wifi网络连接状态
//    	Toast.makeText(getApplicationContext(), "WIFI的连接状态：" + wifi.toString(), Toast.LENGTH_SHORT).show();
		return result;
    }
    
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(br);
	}
//	public OpenfireNetService() {
//		// TODO Auto-generated constructor stub
//	}
	public void setConfig(String hostIP) {
		connectionConfig = null;
		connectionConfig = new ConnectionConfiguration(hostIP, 5222, "");
		if (mConnection.isConnected())
			mConnection.disconnect();
		mConnection = null;
		mConnection = new XMPPConnection(connectionConfig);
	}
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		getListHander().sendEmptyMessage(CONNECT_TO_SERVICER);
		BaseScreen.mOpenfireService = this;
		//好友申请监听
//		OpenfireNetService.getXMPPConnection().addPacketListener(new PacketListener() {
//			
//			@Override
//			public void processPacket(Packet packet) {
//				Presence presence = (Presence) packet;
//				if(presence.getType() == Type.subscribe)
//				{
//					if(BaseScreen.roster!=null)
//					{
//						if(BaseScreen.roster.contains(presence.getFrom()))
//						{
//							Presence subscription = new Presence(Presence.Type.subscribe);
//							subscription.setFrom(BangBangChat.user.getUserId());
//							subscription.setTo(presence.getFrom());
//							OpenfireNetService.getXMPPConnection().sendPacket(subscription);
//							return;
//						}
//					}
//					SystemMessage message;
//					{
//						message = new SystemMessage(BangBangChat.user.getUserId(),presence.getFrom(),presence.getTo(),presence.getType().toString(),true);
//						BaseScreen.sysDB.insert(message);
//						Main.sMsgCount++;
//					}
//				}	
//			}
//		}, new PacketFilter() {
//			
//			@Override
//			public boolean accept(Packet packet) {
//				if(packet instanceof Presence && ((Presence) packet).getType() == Type.subscribe)
//					return true;
//				else
//					return false;
//			}
//		});
	}
	public boolean start() {
		return true;
	}

	public boolean stop() {
		if(mConnection!=null && mConnection.isConnected() && mConnection.isAuthenticated())
		{
			FrCall.user.getvCard().setField(User.VCARD_FIELD_ONLINE_STATUS, "不在线");
			FrCall.user.save();
			new OpenfireTask().execute(OpenfireTask.LOGOUT_TASK,OpenfireNetService.this);
		}
		else
			return true;
//		Logout();
		while(mConnection.isAuthenticated())
		{
			 ;
		}
		return true;
	}
	public class tempTask extends AsyncTask<Object, Object, Object>
	{

		@Override
		protected Object doInBackground(Object... params) {
			toastText = "";
			
			{
				SystemMessage message = (SystemMessage) params[0];
				BaseScreen.sysDB.insert(message);
				Main.sMsgCount++;
			}
			ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_NEW_MSG);
			return true;
		}
		
	}
	public static XMPPConnection getXMPPConnection() {
		return mConnection;
	}
	final public static int SCREEN_HOME_HANDLE_REFRESH_NEW_MSG = 13;
	public static String toastText = "";
	public static int toastTime = Toast.LENGTH_SHORT;
	private  Handler ListHander = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			Bundle bundle= msg.getData();
			switch (msg.what) {
			case SCREEN_HOME_HANDLE_REFRESH_NEW_MSG:
				Main.mTVMsgCount.setText(Main.sMsgCount + "");
				Main.mTVMsgCount.setVisibility(View.VISIBLE);
				Main.mTVMsgCount.invalidate();
				break;
			case CONNECT_TO_SERVICER:
				new OpenfireTask().execute(OpenfireTask.CONNECT_TASK,OpenfireNetService.this);
				break;
			case RESPONSE_CONNECT_TO_SERVICER:
			{
				Intent res = new Intent(resources.getString(R.string.OPENFIRE_ACTION_RES_CONNECT));
				res.putExtra(resources.getString(R.string.RES_LOGIN_RESULT), mConnection.isConnected());
				sendBroadcast(res);
			}
				break;
			case REQUEST_LOGIN:
				//好友申请监听
				getXMPPConnection().addPacketListener(new PacketListener() {
					
					@Override
					public void processPacket(Packet packet) {
						if(packet instanceof Presence)
						{
							Presence presence = (Presence) packet;
							if(presence.getType() == Type.subscribe)
							{
								SystemMessage message;
								{
									Log.v("Presence","收到请求"+presence.toString());
									message = new SystemMessage(presence.getTo(),presence.getFrom(),presence.getTo(),presence.getType().toString(),true);
									Main.mNewMessageList.add(message);
									SystemMessageManager.checkMessage.start();
								}
								ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_NEW_MSG);
							}
						}
					}
				}, new PacketFilter() {
					
					@Override
					public boolean accept(Packet packet) {
//						if(packet instanceof Presence && ((Presence) packet).getType() == Type.subscribe)
//							return true;
//						else
							return !false;
					}
				});
				
				String username = bundle.getString(resources.getString(R.string.REQ_LOGIN_USERNAME));
				String password = bundle.getString(resources.getString(R.string.REQ_LOGIN_PASSWORD));
				String status = bundle.getString(resources.getString(R.string.REQ_LOGIN_STATUS));
				HostIP = Engine.getInstance().getConfigurationService().getString(NgnConfigurationEntry.NETWORK_PCSCF_HOST, NgnConfigurationEntry.DEFAULT_NETWORK_PCSCF_HOST).trim();
				new OpenfireTask().execute(OpenfireTask.LOGIN_TASK,OpenfireNetService.this,username,password,status.equals("true")?Type.unavailable:Type.available);
//				if(!mConnection.isConnected())
//					connectToService(HostIP);
//				Login(username, password);
				break;
			case REQUEST_LOGOUT:
				break;
			case RESPONSE_LOGIN_SUCCESS:
			case RESPONSE_LOGIN_FAIL:	
				Intent res = new Intent(resources.getString(R.string.OPENFIRE_ACTION_RES_LOGIN));
					res.putExtra(resources.getString(R.string.RES_LOGIN_RESULT), mConnection.isAuthenticated());
				sendBroadcast(res);
				
				break;
			case REQUEST_LOAD_CARD:
				String userId = bundle.getString(resources.getString(R.string.REQ_CARD_USER));
				new OpenfireTask().execute(OpenfireTask.LOAD_VCARD,OpenfireNetService.this,userId);
				break;
			case RESPONSE_LOAD_CARD:
				boolean load_ok = bundle.getBoolean(resources.getString(R.string.RES_CARD_RESULT));
				userId = bundle.getString(resources.getString(R.string.REQ_CARD_USER));
				res = new Intent(resources.getString(R.string.OPENFIRE_ACTION_RES_LOAD_CARD));
				res.putExtra(resources.getString(R.string.REQ_CARD_USER), userId);
				res.putExtra(resources.getString(R.string.RES_CARD_RESULT), load_ok);
				sendBroadcast(res);
				break;
			default:
				// do something11. break;
			}
		}
	};
	public OpenfireNetService ()
	{
		Connection.DEBUG_ENABLED = true;
//		Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
		connectionConfig = new ConnectionConfiguration(AppConfig.WANGJING_IP, 5222, "");
		mConnection = new XMPPConnection(connectionConfig);
		cm = mConnection.getChatManager();
		fm = new FileTransferManager(mConnection);
		ProviderManager pm = ProviderManager.getInstance();
		configure(pm);
	}
//	public void Login(String username, String password,
//			Presence.Type login_status) {
//		try {
//			if(mConnection.isAuthenticated())
//				return;
//			mConnection.login(username, password);
//		} catch (XMPPException e) {
//			Log.d(TAG, "login::" + e.getXMPPError());
//		}
//		Presence presence = new Presence(login_status);
//		if(login_status!=Type.unavailable)
//			presence.setStatus("在线");
//		presence.setMode(Mode.available);
//		mConnection.sendPacket(presence);
//		userId = mConnection.getUser();
//		if(mConnection.isAuthenticated())
//			ListHander.sendEmptyMessage(RESPONSE_LOGIN_SUCCESS);
//		else
//			ListHander.sendEmptyMessage(RESPONSE_LOGIN_FAIL);
//	}

	
//	public void Login(String username, String password) {
//		 Login(username, password, Presence.Type.available);
//	}

	
	public boolean Logout() {
		if(!mConnection.isConnected())
			return true;
		Presence presence = new Presence(Type.unavailable);
		mConnection.sendPacket(presence);
		mConnection.disconnect();
		return !mConnection.isConnected();
	}
	


	public static void configure(ProviderManager pm) {

		// Private Data Storage
		pm.addIQProvider("query", "jabber:iq:private",
				new PrivateDataManager.PrivateDataIQProvider());

		// Time
		try {
			pm.addIQProvider("query", "jabber:iq:time",
					Class.forName("org.jivesoftware.smackx.packet.Time"));
		} catch (ClassNotFoundException e) {
			Log.w("TestClient",
					"Can't load class for org.jivesoftware.smackx.packet.Time");
		}

		// Roster Exchange
		pm.addExtensionProvider("x", "jabber:x:roster",
				new RosterExchangeProvider());

		// Message Events
		pm.addExtensionProvider("x", "jabber:x:event",
				new MessageEventProvider());

		// Chat State
		pm.addExtensionProvider("active",
				"http://jabber.org/protocol/chatstates",
				new ChatStateExtension.Provider());

		pm.addExtensionProvider("composing",
				"http://jabber.org/protocol/chatstates",
				new ChatStateExtension.Provider());

		pm.addExtensionProvider("paused",
				"http://jabber.org/protocol/chatstates",
				new ChatStateExtension.Provider());

		pm.addExtensionProvider("inactive",
				"http://jabber.org/protocol/chatstates",
				new ChatStateExtension.Provider());

		pm.addExtensionProvider("gone",
				"http://jabber.org/protocol/chatstates",
				new ChatStateExtension.Provider());

		// XHTML
		pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im",
				new XHTMLExtensionProvider());

		// Group Chat Invitations
		pm.addExtensionProvider("x", "jabber:x:conference",
				new GroupChatInvitation.Provider());

		// Service Discovery # Items
		pm.addIQProvider("query", "http://jabber.org/protocol/disco#items",
				new DiscoverItemsProvider());

		// Service Discovery # Info
		pm.addIQProvider("query", "http://jabber.org/protocol/disco#info",
				new DiscoverInfoProvider());

		// Data Forms
		pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());

		// MUC User
		pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user",
				new MUCUserProvider());

		// MUC Admin
		pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin",
				new MUCAdminProvider());

		// MUC Owner
		pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner",
				new MUCOwnerProvider());

		// Delayed Delivery
		pm.addExtensionProvider("x", "jabber:x:delay",
				new DelayInformationProvider());

		// Version
		try {
			pm.addIQProvider("query", "jabber:iq:version",
					Class.forName("org.jivesoftware.smackx.packet.Version"));
		} catch (ClassNotFoundException e) {
			// Not sure what's happening here.
		}
		// VCard
		pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());

		// Offline Message Requests
		pm.addIQProvider("offline", "http://jabber.org/protocol/offline",
				new OfflineMessageRequest.Provider());

		// Offline Message Indicator
		pm.addExtensionProvider("offline",
				"http://jabber.org/protocol/offline",
				new OfflineMessageInfo.Provider());

		// Last Activity
		pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());

		// User Search
		pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());

		// SharedGroupsInfo
		pm.addIQProvider("sharedgroup",
				"http://www.jivesoftware.org/protocol/sharedgroup",
				new SharedGroupsInfo.Provider());

		// JEP-33: Extended Stanza Addressing
		pm.addExtensionProvider("addresses",
				"http://jabber.org/protocol/address",
				new MultipleAddressesProvider());

		// FileTransfer
		pm.addIQProvider("si", "http://jabber.org/protocol/si",
				new StreamInitiationProvider());

		pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",
				new BytestreamsProvider());

		// pm.addIQProvider("open", "http://jabber.org/protocol/ibb",
		// new IBBProviders.Open());
		//
		// pm.addIQProvider("close", "http://jabber.org/protocol/ibb",
		// new IBBProviders.Close());
		//
		// pm.addExtensionProvider("data", "http://jabber.org/protocol/ibb",
		// new IBBProviders.Data());

		// Privacy
		pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());

		pm.addIQProvider("command", "http://jabber.org/protocol/commands",
				new AdHocCommandDataProvider());
		pm.addExtensionProvider("malformed-action",
				"http://jabber.org/protocol/commands",
				new AdHocCommandDataProvider.MalformedActionError());
		pm.addExtensionProvider("bad-locale",
				"http://jabber.org/protocol/commands",
				new AdHocCommandDataProvider.BadLocaleError());
		pm.addExtensionProvider("bad-payload",
				"http://jabber.org/protocol/commands",
				new AdHocCommandDataProvider.BadPayloadError());
		pm.addExtensionProvider("bad-sessionid",
				"http://jabber.org/protocol/commands",
				new AdHocCommandDataProvider.BadSessionIDError());
		pm.addExtensionProvider("session-expired",
				"http://jabber.org/protocol/commands",
				new AdHocCommandDataProvider.SessionExpiredError());
	}

	
	public UserSearchManager getUserSearchManager() {
		if (search == null) {
			search = new UserSearchManager(this.getXMPPConnection());
			searchService = "";
			Collection<String> services;
			try {
				services = search.getSearchServices();
				for (String string : services) {
					if (string.indexOf("search") >= 0) {
						searchService = string;
						break;
					}
				}
				return search;
			} catch (XMPPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		} else
			return search;
	}

	
	public String getUserSearchService() {
		// TODO Auto-generated method stub
		return searchService;
	}
	
	
	/**
	 * 获取聊天管理
	 */
	
	public ChatManager getChatManager() {
		return cm;
	}
	
	/**
	 * 创建聊天
	 */
	
	public Chat getChat(String user) {
		return cm.createChat(user, null);
	}
	
	/**
	 * 获取文件管理
	 */
	
	public FileTransferManager getFileTransferManager() {
		return fm;
	}
	
	/**
	 * 创建输出的文件传输
	 */
	
	public OutgoingFileTransfer getOutgoingFileTransfer(String user) {
		return fm.createOutgoingFileTransfer(user);
	}

	
	public static VCard getVcard(String userId) {
		setTempCard(new VCard());
		try {
			getTempCard().load(mConnection, userId);
		} catch (XMPPException e) {
			Toast.makeText(FrCall.getContext(), e.getXMPPError().getMessage(), Toast.LENGTH_SHORT);
			return null;
		}
		return getTempCard();
	}

	
	public String getLoginUser() {
		return userId;
	}

	
	public void saveVcard(VCard card) {
		if(card!=null)
		{
			try {
				card.save(mConnection);
			} catch (XMPPException e) {
				e.printStackTrace();
			}
		}
	}	

//	private void broadcastLoginEvent(NgnOpenfireEventArgs args){
//		final Intent intent = new Intent(NgnOpenfireEventArgs.ACTION_LOGIN_EVENT);
//		intent.putExtra(NgnOpenfireEventArgs.EXTRA_EMBEDDED, args);
//		NgnApplication.getContext().sendBroadcast(intent);
//	}

	
	public IBinder onBind(Intent intent) {
		return serviceBinder;
	}
	public void setListHander(Handler listHander) {
		ListHander = listHander;
	}
	public Handler getListHander() {
		return ListHander;
	}
	public static void setTempCard(VCard tempCard) {
		OpenfireNetService.tempCard = tempCard;
	}
	public static VCard getTempCard() {
		return tempCard;
	}
}
